import CreateModal from '@/pages/Admin/Book/components/CreateModal';
import UpdateModal from '@/pages/Admin/Book/components/UpdateModal';
import { deleteBookUsingPost, listBookByPageUsingGet } from '@/services/backend/bookController';
import { PlusOutlined, ExportOutlined } from '@ant-design/icons'; // 添加导出图标
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import '@umijs/max';
import { Button, message, Space, Typography, Statistic, Table } from 'antd';
import React, { useRef, useState } from 'react';
import * as XLSX from 'xlsx'; // 导入Excel库

/**
 * 顾客管理页面
 *
 * @constructor
 */
const BookAdminPage: React.FC = () => {
  // 是否显示新建窗口
  const [createModalVisible, setCreateModalVisible] = useState<boolean>(false);
  // 是否显示更新窗口
  const [updateModalVisible, setUpdateModalVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  // 当前用户点击的数据
  const [currentRow, setCurrentRow] = useState<API.Book>();
  // 存储消费金额总和
  const [saleTotal, setSaleTotal] = useState<number>(0);
  // 存储表格数据
  const [tableData, setTableData] = useState<API.Book[]>([]);

  /**
   * 删除节点
   *
   * @param row
   */
  const handleDelete = async (row: API.Book) => {
    const hide = message.loading('正在删除');
    if (!row) return true;
    try {
      await deleteBookUsingPost({
        id: row.id as any,
      });
      hide();
      message.success('删除成功');
      actionRef?.current?.reload();
      return true;
    } catch (error: any) {
      hide();
      message.error('删除失败，' + error.message);
      return false;
    }
  };

  /**
   * 导出Excel文件
   */
  const exportToExcel = () => {
    if (tableData.length === 0) {
      message.warning('没有数据可导出');
      return;
    }

    // 准备导出的数据（只包含需要的列）
    const exportData = tableData.map(item => ({
      顾客id: item.visitorId,
      顾客姓名:item.visitorName,
      顾客电话:item.visitorPhone,
      顾客第二电话:item.visitorSecondPhone,
      顾客预订日期:item.bookDay,
      顾客预订时间:item.bookTime === 0 ? '中午' : '晚上',
      顾客预订人数:item.bookPeople,
      顾客预订桌数:item.bookTable,
      顾客预订人均消费水平:item.bookLevel,
      顾客预订总金额:item.bookSum,
      顾客预订状态:item.bookStatus === 0 ? '已预约' : item.bookStatus === 1 ? '已结账' : '已取消',
      创建时间:item.createTime,
      更新时间:item.updateTime
    }));

    // 创建工作簿和工作表
    const worksheet = XLSX.utils.json_to_sheet(exportData);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, '预订数据');

    // 生成Excel文件并下载
    XLSX.writeFile(workbook, `预订数据_${new Date().toLocaleString().replace(/[/:\\]/g, '_')}.xlsx`);
    message.success('导出成功');
  };

  /**
   * 表格列配置
   */
  const columns: ProColumns<API.Book>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      valueType: 'text',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '顾客id',
      dataIndex: 'visitorId',
      valueType: 'text',
      hideInForm:true,
      hideInSearch: true,
      hideInTable:true,
    },
    {
      title: '顾客姓名',
      dataIndex: 'visitorName',
      valueType: 'text',
    },
    {
      title: '顾客电话',
      dataIndex: 'visitorPhone',
      valueType: 'text',
    },
    {
      title: '顾客第二电话',
      dataIndex: 'visitorSecondPhone',
      valueType: 'text',
    },
    {
      title: '顾客预订日期',
      dataIndex: 'bookDay',
      valueType: 'date',
    },
    {
      title: '顾客预订时间',
      dataIndex: 'bookTime',
      valueEnum:{
        0:{text:'中午'},
        1:{text:'晚上'},
      },
    },
    {
      title: '顾客预订人数',
      dataIndex: 'bookPeople',
      valueType: 'text',
    },
    {
      title: '顾客预订桌数',
      dataIndex: 'bookTable',
      valueType: 'text',
    },
    {
      title: '顾客预订人均消费水平',
      dataIndex: 'bookLevel',
      valueType: 'text',
    },
    {
      title: '顾客预订总金额',
      dataIndex: 'bookSum',
      valueType: 'text',
      hideInForm: true,
    },
    {
      title: '顾客预订状态',
      dataIndex: 'bookStatus',
      valueEnum: {
        0: {text: '已预约',},
        1: {text: '已结账',},
        2: {text: '已取消',},
      },
    },
    {
      title: '创建时间',
      sorter: true,
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '更新时间',
      sorter: true,
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <Space size="middle">
          <Typography.Link
            onClick={() => {
              setCurrentRow(record);
              setUpdateModalVisible(true);
            }}
          >
            修改
          </Typography.Link>
          <Typography.Link type="danger" onClick={() => handleDelete(record)}>
            删除
          </Typography.Link>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer>
      <ProTable<API.Book>
        headerTitle={'预订记录管理'}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        // 添加汇总行
        // summary={() => (
        //   <Table.Summary fixed>
        //     <Table.Summary.Row>
        //       <Table.Summary.Cell index={0} colSpan={6}>
        //         <Statistic
        //           title="消费金额(打折后) 总和"
        //           value={saleTotal}
        //           precision={2}
        //           valueStyle={{ color: '#cf1322', fontWeight: 'bold' }}
        //         />
        //       </Table.Summary.Cell>
        //     </Table.Summary.Row>
        //   </Table.Summary>
        // )}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setCreateModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
          // 添加导出按钮
          <Button
            key="export"
            type="default"
            onClick={exportToExcel}
            icon={<ExportOutlined />}
          >
            导出Excel
          </Button>
        ]}
        request={async (params, sort, filter) => {
          const sortField = Object.keys(sort)?.[0];
          const sortOrder = sort?.[sortField] ?? undefined;
          const { data, code } = await listBookByPageUsingGet({
            ...params,// 这里包含了搜索栏的所有参数
            sortField,
            sortOrder,
            ...filter,
          } as API.BookQueryRequest);

          if (code === 0 && data) {
            // 存储表格数据用于导出
            setTableData(data.records || []);

            // 计算消费金额(打折后)总和
            // if (data.records && data.records.length > 0) {
            //   const total = data.records.reduce((sum: number, item: API.Book) => {
            //     // 将字符串转换为数字，无法转换的视为0
            //     const saleValue = parseFloat(item.bookSale as string) || 0;
            //     return sum + saleValue;
            //   }, 0);
            //   setSaleTotal(total);
            // } else {
            //   setSaleTotal(0);
            // }
          }

          return {
            success: code === 0,
            data: data?.records || [],
            total: Number(data?.total) || 0,
          };
        }}
        columns={columns}
      />
      <CreateModal
        visible={createModalVisible}
        columns={columns}
        onSubmit={() => {
          setCreateModalVisible(false);
          actionRef.current?.reload();
        }}
        onCancel={() => {
          setCreateModalVisible(false);
        }}
      />
      <UpdateModal
        visible={updateModalVisible}
        columns={columns}
        oldData={currentRow}
        onSubmit={() => {
          setUpdateModalVisible(false);
          setCurrentRow(undefined);
          actionRef.current?.reload();
        }}
        onCancel={() => {
          setUpdateModalVisible(false);
        }}
      />
    </PageContainer>
  );
};
export default BookAdminPage;
